package com.bwhk.splitdata.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {

	public static String toJson(Object obj) {
		ObjectMapper mapper = new ObjectMapper();
		String json="";
		try {
			json = mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			
		}
		String newJson="";
		
		try {
			byte[] b = json.getBytes("UTF-8");
			
			newJson = new String(b);
		} catch (UnsupportedEncodingException e) {
			
		}
		
		return newJson;
		
	}
	
	public static <T>Object toObject(String json,Class<T> valueType) {
		ObjectMapper mapper = new ObjectMapper();
		
		byte[] bytes=null;
		try {
			bytes = json.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		Object obj=null;
		try {
			 obj =  mapper.readValue(bytes, valueType);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return obj;
	}
}
